<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb20">
      <el-radio-group v-model="current" @input="stateHandel">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button :label="item.value" v-for="(item, index) in dict.type.order_tab" :key="index">{{
            item.label
          }}
        </el-radio-button>
      </el-radio-group>
    </el-row>
    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['order:order:add']">新建预定订单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="房源" prop="premisesAddress">
        <el-input v-model="queryParams.premisesAddress" placeholder="请输入" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="reserveUser">
        <el-input v-model="queryParams.reserveUser" placeholder="请输入" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="reserveUserPhone">
        <el-input v-model="queryParams.reserveUserPhone" placeholder="请输入" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来源" prop="orderSource">
        <el-select v-model="queryParams.orderSource" placeholder="订单来源" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.order_source" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="入住时间" prop="dateRange">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="orderState">
        <el-select v-model="queryParams.orderState" placeholder="订单状态" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.order_state" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="单号" prop="orderId">
        <el-input v-model="queryParams.orderId" placeholder="请输入" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="roomList" @selection-change="handleSelectionChange" ref="table" v-loading="loading">
      <el-table-column label="单号" prop="orderId" :show-overflow-tooltip="true"/>
      <el-table-column label="房源" prop="premisesAddress" :show-overflow-tooltip="true"/>
      <el-table-column label="联系人" prop="" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div v-if="scope.row.orderLessee && scope.row.orderLessee.lesseeType == 2">
            <div>{{ scope.row.orderLessee.enterpriseName }}</div>
            <div>{{ scope.row.orderLessee.phone }}</div>
          </div>
          <div v-else>
            <div>{{ scope.row.reserveUser }}</div>
            <div>{{ scope.row.reserveUserPhone }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="来源" prop="orderSource">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_source" :value="scope.row.orderSource"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="金额" prop="">-->
<!--        <template slot-scope="scope">-->
<!--          <template v-if="scope.row.orderState == 1">-->
<!--            <div>已付租金：{{ scope.row.rentPaidNumber }}</div>-->
<!--            <div>已付押金：{{ scope.row.depositPaidNumber }}</div>-->
<!--          </template>-->
<!--          <template v-else>-->
<!--            <div>-->
<!--              租金：{{-->
<!--                scope.row.rentalMode == 1-->
<!--                  ? scope.row.monthRent-->
<!--                  : scope.row.totalRent-->
<!--              }}-->
<!--            </div>-->
<!--            <div>押金：{{ scope.row.deposit }}</div>-->
<!--          </template>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column label="入住时间" prop="checkInTime">
        <template slot-scope="scope">
          <div>
            入住：{{ scope.row.checkInTime | formatDate('YYYY-MM-DD') }}
          </div>
          <div>
            退租：{{ scope.row.checkOutTime | formatDate('YYYY-MM-DD') }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="orderState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_state" :value="scope.row.orderState"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleDetail(scope.row)">订单详情</el-button>
          <el-button size="mini" type="text" @click="handleContractInfo(scope.row)"
                     v-if="enterprises.contractStatus==1 && scope.row.orderState != 3"
          >
            合同信息
          </el-button>
          <el-button size="mini" type="text" @click="handleCheckIn(scope.row)" v-if="scope.row.orderState == 1">入住
          </el-button>
          <el-button size="mini" v-if="scope.row.orderState == 7" type="text"
                     @click="surrenderHandel(scope.row)"
          >退租
          </el-button>
          <el-button size="mini" type="text" @click="handleCheck(scope.row)"
                     v-if="['9','14'].includes(scope.row.orderState)"
          >验房
          </el-button>

          <el-button size="mini" type="text" v-if="scope.row.orderState == 1"
                     @click="handleUpdate(scope.row)"
          >预定变更
          </el-button>
          <el-button size="mini" type="text" v-if="scope.row.orderState == 7"
                     @click="reletHandel(scope.row)"
          >续租
          </el-button>
          <el-button size="mini" type="text" @click="handleChangeHouse(scope.row)"
                     v-if="scope.row.orderState == 7"
          >换房
          </el-button>
          <el-button size="mini" type="text" v-if="scope.row.orderState == 7"
                     @click="subletHandel(scope.row)"
          >转租
          </el-button>

          <el-button size="mini" type="text" v-if="scope.row.orderState == 1"
                     @click="cancellation(scope.row)"
          >作废
          </el-button>
<!--          <el-button size="mini" type="text" v-if="scope.row.orderState == 1"-->
<!--                     @click="signHandel(scope.row)"-->
<!--                     :disabled="scope.row.newContractFlag === '0'"-->
<!--          >签约-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />
    <!-- 详情 -->
    <order-detail v-if="detailDialogVisible" v-model="detailDialogVisible" :orderId="orderId"></order-detail>
    <!-- 换房 -->
    <change-house v-model="openChangeHouse" :orderId="orderId" @success="dialogClose" :data="form"/>
    <!-- 转租 -->
    <sublet v-model="openSublet" :orderId="orderId" @success="dialogClose" />

    <!-- 新增 -->
    <orderAdd v-model="addDialogVisible" :orderId="orderId" @success="handleQuery" :title="orderTitle"></orderAdd>

    <!-- 签约 -->
    <order-sign v-if="signDialogVisible" v-model="signDialogVisible" :orderId="orderId" @success="handleQuery"
                :changeInfo="changeInfo" :isRelet="isRelet" :subletTime="subletTime" :title="signTitle"
                @input="colseSign"
    ></order-sign>
    <!-- 退租 -->
    <order-surrender v-model="surrenderDialogVisible" :orderId="orderId" @success="handleQuery"></order-surrender>
    <!-- 验房 -->
    <check-house v-if="openCheck" v-model="openCheck" :orderId="orderId" @input="getList"
                 @submit="changeSubmit"
    ></check-house>
    <!--  合同信息  -->
    <ContractInfo v-model="contractInfoOption.visible" :title="contractInfoOption.title" :data="contractInfoOption.data"
                  @success="handleQuery"
    />
    <!--  入住  -->
    <CheckIn v-model="checkInOption.visible" :title="checkInOption.title" :data="form" @success="handleQuery"/>
    <!--  续租  -->
    <Relet v-model="openRelet" :orderId="orderId" :data="form" @success="handleQuery"/>

    <AddContractSign v-model="addContractSignDialogVisible" title="新增合同" @success="getList" :form-data="form"
                     :isSigning="true"
    />
  </div>
</template>

<script>
import { listOrder, cancelOrder } from '@/api/order/order'
import orderDetail from './component/order-detail.vue'
import changeHouse from './component/change-house.vue'
import checkHouse from './component/check-house.vue'
import sublet from './component/sublet.vue'
import orderEdit from './component/order-edit.vue'
import orderAdd from './component/order-add.vue'
import orderSign from './component/order-sign.vue'
import orderSurrender from './component/order-surrender.vue'
import membershipRegistration from './component/membership-registration.vue'

import ContractInfo from '@/views/long-short-rent/order/component/contract-info.vue'
import CheckIn from '@/views/long-short-rent/order/component/check-in.vue'
import Relet from '@/views/long-short-rent/order/component/relet.vue'

// 添加合同并签约
import AddContractSign from '@/views/long-short-rent/contract/lessee/components/add.vue'

import { mapGetters } from 'vuex'
import Add from '@/views/long-short-rent/contract/lessee/components/add.vue'

export default {
  name: 'orderList',
  dicts: ['order_state', 'order_source', 'order_tab'],
  components: {
    Add,
    orderDetail,
    changeHouse,
    orderEdit,
    orderAdd,
    membershipRegistration,
    orderSign,
    orderSurrender,
    sublet,
    checkHouse,
    ContractInfo,
    CheckIn,
    Relet,
    AddContractSign
  },
  data() {
    return {
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      roomList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 当前选择
      current: '',
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuNodeAll: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roomNumber: undefined,
        premisesAddress: undefined,
        status: undefined,
        orderState: undefined,
        orderIds: undefined,
        reserveUser: '',
        reserveUserPhone: '',
        orderSource: undefined,
        checkInTime: '',
        checkOutTime: '',
        orderId: ''
      },
      // 表单参数
      form: {},
      orderId: '',
      openChangeHouse: false,
      openEdit: false,
      orderInfo: {},
      addDialogVisible: false, //新建弹窗，
      openmembershipRegistration: false,
      addContractSignDialogVisible: false, //新增合同并签约弹窗
      idEdit: false, //是否编辑成员
      isRelet: false, //是否续租
      signDialogVisible: false, //签约弹窗
      detailDialogVisible: false,
      surrenderDialogVisible: false, //退租弹窗
      changeInfo: {},
      openSublet: false,
      subletTime: '',
      signTitle: '',
      openCheck: false,
      orderTitle: '',

      contractInfoOption: {
        visible: false,
        title: '合同信息'
      },
      checkInOption: {
        visible: false,
        title: '入住信息'
      },
      openRelet: false //续租弹窗
    }
  },
  computed: {
    ...mapGetters(['enterprises'])
  },
  created() {
    this.getList()
  },
  activated() {
    this.getList()
  },
  methods: {
    //重置数据
    colseSign(e) {
      this.isRelet = false
      this.orderId = ''
      this.changeInfo = {}
      this.subletTime = ''
      this.signTitle = ''
    },
    reletHandel(row) {
      this.orderId = row.orderId
      // this.signDialogVisible = true
      this.isRelet = true
      this.form = { ...row }
      this.openRelet = true
      this.signTitle = '续签'
    },
    subletHandel(row) {
      this.orderId = row.orderId
      this.openSublet = true
      this.signTitle = '转租'
    },
    changeSubmit(row) {
      this.changeInfo = row
      this.openChangeHouse = false
      this.signDialogVisible = true
      this.signTitle = '换房'
    },
    subletSubmit(time) {
      console.log('time', time)
      this.subletTime = time
      this.openSublet = false
      this.signDialogVisible = true
    },
    surrenderHandel(row) {
      this.orderId = row.orderId
      this.surrenderDialogVisible = true
    },
    signHandel(row) {
      // this.orderId = row.orderId
      // this.signDialogVisible = true

      this.form = { ...row }
      this.addContractSignDialogVisible = true
    },
    cancellation(row) {
      this.$confirm('作废后无法恢复，请谨慎操作  ', '确定订单作废?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          cancelOrder(row.orderId).then((response) => {
            this.$message.success('操作成功')
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    dialogClose() {
      this.openChangeHouse = false
      this.openEdit = false
      this.openmembershipRegistration = false
      this.getList()
    },
    stateHandel(i) {
      let orderState = i
      this.queryParams.orderTab = orderState
      this.handleQuery()
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      this.queryParams.checkInTime = this.dateRange[0]
      this.queryParams.checkOutTime = this.dateRange[1]
      listOrder(this.queryParams, this.dateRange).then((response) => {
        this.roomList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.orderId)
      this.single = selection.length != 1
      this.multiple = !selection.length
      this.queryParams.orderIds = this.ids
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.orderId = ''
      this.orderTitle = '新建订单'
      this.addDialogVisible = true
    },
    // 详情操作
    handleDetail(row) {
      this.orderId = row.orderId
      this.detailDialogVisible = true
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      this.orderId = row.orderId
      this.orderTitle = '预定变更'
      this.addDialogVisible = true
    },
    //换房操作
    handleChangeHouse(row) {
      this.orderId = row.orderId
      this.form = { ...row }
      this.openChangeHouse = true
    },
    //验房
    handleCheck(row) {
      this.orderId = row.orderId
      this.openCheck = true
    },
    // 合同信息
    handleContractInfo(row) {
      this.contractInfoOption = {
        visible: true,
        title: '合同信息',
        data: { ...row }
      }
    },
    //入住
    handleCheckIn(row) {
      console.log('row', row)
      if (row.contractSignFlag == 0) {
        this.$confirm('房间未完成合同签署，确认继续入住?', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => {
          this.checkInOption.visible = true
          this.checkInOption.title = '入住'
          this.form = { ...row }
        }).catch((err) => {
          console.log(err)
        })
      }else{
        this.checkInOption.visible = true
        this.checkInOption.title = '入住'
        this.form = { ...row }
      }

    },
    //请空选择项
    clearSelect() {
      this.$refs.table.clearSelection()
    }
  }
}
</script>
<style lang="scss" scoped>
.title {
  font-size: 14px;
  font-weight: 500;
  color: #666;
}

.total {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-top: 6px;
}

.left-border {
  border-left: 1px solid #999;
}

.right-border {
  border-right: 1px solid #999;
}

.info {
  padding: 10px 15px;
  margin: 15px 0;
  background: #e6f7ff;
  color: #1890ff;

  span {
    color: #565c5f;
  }

  .clear {
    margin-left: 20px;
    cursor: pointer;
  }
}
</style>
